<template>
	<view>
		<cu-custom bgColor="bg-white" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">订单确认</block>
		</cu-custom>
		<div class="order">
			<div class="cartlist">
				<uni-table stripe emptyText="暂无更多数据">
					<!-- 表头行 -->
					<uni-tr style="background-color: #CCFFFF">
						<uni-th align="left" width="120">名称</uni-th>
						<uni-th align="right" width="10">单价</uni-th>
						<uni-th align="right" width="10">数量</uni-th>
						<uni-th align="right" width="20">小计</uni-th>
					</uni-tr>
					<!-- 表格数据行 -->
					<!-- 不显示辣椒油、榨菜-->
					<uni-tr v-for="(item,index) in listData" :key="index" v-if="item.productCode != 715001 && item.productCode != 715002 ">
						
						<uni-td align="left" >{{item.productName}}</uni-td>
							
						<uni-td align="right" class="price">{{item.price}}</uni-td>
						
						<uni-td align="right" v-if="item.productCode == 715001">{{parseFloat(item.num*3/500).toFixed(3)}}</uni-td>
						<uni-td align="right" v-else-if="item.productCode == 715002">{{parseFloat(item.num*9/500).toFixed(3)}}</uni-td>
						<uni-td align="right" v-else-if="item.productCode == 715003">{{parseFloat(item.num*4.5/500).toFixed(3)}}</uni-td>
						
						<uni-td align="right" v-else>{{parseFloat(item.num).toFixed(0)}}</uni-td>
						
						<uni-td align="right" class="price">{{parseFloat(item.price * item.num).toFixed(2)}}</uni-td>
						
					</uni-tr>
					
				</uni-table>

			</div>
			<view class="cu-form-group" style="border-bottom: 1px solid #ccc;">
				<view class="title">订货日期</view>
				<view class="picker">{{date}}</view>
				<!-- <picker mode="date" :value="date" :start="startDate" :end="endDate" @change="DateChange">
					<view class="picker">{{date}}</view>
				</picker> -->
			</view>
			
			<div class="desc">
			  <uni-easyinput type="textarea" autoHeight v-model="fnote" placeholder="请输入备注内容..."></uni-easyinput>
			</div>
			<div class="bottom">
				<div class="price">合计: {{parseFloat(finalAmount).toFixed(2)}}元 (共{{totalNum}}件)</div>
				<div @click="pay">提交订单</div>
			</div>
		</div>
		
		<view class="cu-form-group" style="border-bottom: 0px solid #ccc;">
			
		</view>
	</view>
</template>

<script>
	import {
		uniTable
	} from '@dcloudio/uni-ui'
	import {
		toLogin,
		formatDate,
		getStorageUserInfo,
		getStorageCartInfo,
		setStorageCartInfo
	} from "@/server/api.js";

	import {
		orderSaveCartApi,
		checkOverDepositApi,
		calcFreightFee
	} from "@/server/config.js"
	let _ = require('lodash');
	export default {
		async onLoad(options) {
			let ids = options.ids
			this.listData = []
			if (!ids) {
				//页面导航
				uni.switchTab({
					url: "/pages/my/main"
				});
				return
			}
			let cart = getStorageCartInfo()
			
			if (cart && cart.length > 0) {
				let list = [];
				ids.split(',').forEach(function(id) {
					list = list.concat(cart.filter(item => item.id == id))
				})
				this.listData = list

				let totalNum = 0
				let totalPrice = 0
				this.listData.forEach(p => {
					if(p.productCode != 715001 && p.productCode != 715002 && p.productCode != 715003){
						totalNum += parseInt(p.num, 10);
					}
					totalPrice += p.num * p.price
				})
				this.totalNum = totalNum
				this.finalAmount = totalPrice
			}
		
			//包子加辣椒油
			//categoryName : 大分类名称
			//prodcutCode: 商品分类code
			//productName: 商品名称,
			//specCode : 规格code
			//specName: 规格名称
			
			this.addExtraProduct('lajiaoyou','715001','辣椒油包','','斤')
			this.addExtraProduct('zhacai','715002','榨菜','','斤')
			this.addExtraProduct('xiangcong','715003','香葱','','斤')
			this.addExtraProduct('liaobao','603163','馄饨料包','','袋')
			this.addExtraProduct('xiaohuntun','715013','小馄饨料粉','','袋')
			
			console.info(this.listData)
			
			let user = getStorageUserInfo();
			if(user) {
				try {
					let res = await calcFreightFee({
						amount: this.finalAmount
					})
					console.log(res)
					if (res.statusCode === 200) {
						let orderFee = res.data.freightFee
						if (orderFee > 0) {
							this.listData.push({
								productCode:'yunfei',
								productName:'运费',
								num:1,
								price: orderFee,
								specCode:'',
								specName:''
							})
							this.finalAmount = this.finalAmount + orderFee
						}
					}
				} catch(e) {
					
				}
				// //起订量
				// let orderQty = user.orderQty || 0
				// //运费
				// let freightFee = user.freightFee || 0
				
				// let orderFee = freightFee;
				
				// //起订量大于0的情况
				// if(orderQty > 0){
					
				// 	//订单金额合计大于起订金额就免费
				// 	if(this.finalAmount > orderQty){
				// 		orderFee = 0
				// 	}
				// }
				
				// //运费大于零的时候显示运费
				// if(orderFee > 0){
				// 	this.listData.push({
				// 		productCode:'yunfei',
				// 		productName:'运费',
				// 		num:1,
				// 		price:orderFee,
				// 		specCode:'',
				// 		specName:''
				// 	})
				// 	this.finalAmount = this.finalAmount + orderFee
				// }
			}
			
			this.date = formatDate(this.addDate(new Date(),1))
		},
		onShow() {
			toLogin();
		},
		onUnload() {

		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		created() {},
		mounted() {},
		data() {
			return {
				address: {},
				productId: "",
				date: '',
				fnote:'',
				totalNum: 0,
				finalAmount: 0,
				superpack: 'false',
				result_spike: 'false',
				loading: false,
				listData:[]
			};
		},
		components: {
			uniTable
		},
		methods: {
			DateChange: function(e) {
				this.date = e.target.value
			},
			addDate(date, days) {
			    if (days == undefined || days == '') {
			        days = 1;
			    }
			    var date = new Date(date);
			    date.setDate(date.getDate() + days);
			    return date;
			},
			getDate(type) {
				var date = this.addDate(Date(),1);
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				date = new Date(date)
				if (type === 'end') {
					year = year + 1;
				}
				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			async pay() {
				if (this.loading) return
				this.loading = true
				let postData = []
				let totalAmount = 0
				this.listData.forEach(p => {
					postData.push({
						productCode: p.productCode,
						materialName:p.productName,
						fqty: parseInt(p.num, 10),
						price: parseFloat(p.num * p.price).toFixed(3), //价格保留小数点后3位
						specCode: p.specCode,
						specName: p.specName,
						fDeliveryDate: this.date,
						taocanDetail: p.taocanDetail
					})
					totalAmount = parseFloat(totalAmount) + parseFloat(p.num * p.price)
				})
				let _this = this;
				
				let result = await checkOverDepositApi({checkOrderAmount : totalAmount.toFixed(3)})
				let checkData = result.data.records[0]
				if (!checkData.flag) {
					uni.showToast({
						title: "预付金额不足[订单金额:"+ checkData.orderAmt +",预付金额: "+ checkData.depositAmt +",可超预付金额:"+ checkData.overdepositAmt +"]，不能下单!",
						icon: 'none',
						mask: true, 
						duration: 2500
					})
					this.loading = false
				} else {
					orderSaveCartApi({
						fnote:_this.fnote,//订单备注
						productInfos: postData
					}).then(function(res) {
						if(res.statusCode == 400){
							let errs = res.data.errors;
							errs.forEach(p=>{
								if(p.code == "CM008"){
									uni.showToast({
										title: p.message, //提示的内容,
										duration: 2000, //延迟时间,
										icon: "none",
										mask: true, //显示透明蒙层，防止触摸穿透,
										success: res => {}
									});
									_this.loading = false
									return
								}
							})
							this.loading = false
							return
						}
						
						uni.showToast({
							title: "订单成功已提交",
							duration: 500
						})
						
						//删除购物车里的项目
						_this.listData.forEach(function(data) {
							let cart = getStorageCartInfo()
							let index = cart.find(p => p.id == data.id)
							cart.splice(index, 1)
							setStorageCartInfo(cart)
						})
						
						setTimeout(function() {
							uni.switchTab({
								url: "/pages/my/main"
							});
						}, 1000)
					}).catch(function(res) {
						this.loading = false
						uni.showToast({
							icon: "none",
							title: "订单提交失败,请稍后重试",
						})
					})
				}
			},
			
			// 料包等份数处理
			addExtraProduct(prop,prodcutCode,prodcutName,specCode,specName){
				let key = prop;
				let result = _.cloneDeep(_.filter(this.listData, function(o){
					return o[prop]
				}))
				
				result.forEach(p => {
					p.num = p.num * (prop == "liaobao" ? (p.specNum || 1) : 1)
				})
				
				let sum = 0
				let count = _.reduce(_.map(result,'num'), function(sum, n) {
				  return sum + n;
				}, 0);
				
				if(count > 0){
					this.listData.push({
						productCode:prodcutCode,
						productName:prodcutName,
						num:count,
						price:0,
						specCode:'',
						specName:specName
					})
					//this.totalNum = this.totalNum + count
				}
			}
		},
	};
</script>
<style lang='scss' scoped>
	@import "./style";
</style>+
